package popple.display
{

	import flash.display3D.Context3D;
	import flash.display3D.Context3DTextureFormat;
	import flash.display3D.textures.Texture;
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Matrix3D;
	import flash.geom.Rectangle;
	
	import popple.core.RenderHelper;
	import popple.core.renders.NormalRender;

	/**
	 *最小单元显示对象,可做单元图形显示，也可以单个位图显示
	 * @author Popple
	 * 
	 */	
	public class Sprite extends DisplayObjectContainer
	{
		protected var mDraged:Boolean=false;
		protected var mDragCenter:Boolean=false;
		
		private var _offsetX:Number;
		private var _offsetY:Number;
		protected var mBitmap:TBitmap;
		protected var mTexture:Texture;
		
		
					  
		protected var mRender:NormalRender;
		private var mUVRect:Rectangle;
		/**
		 *位图源 
		 * @param bitmap
		 * @example
		 * <listing version="3.0">
		   var bd:BitmapData=new BitmapData(64,128,true,0xffffffff)
           var sprite:Sprite=new Sprite;
		   sprite.bitmap=new TBitmap(bd,new Rectangle(0,0,50,50));
           </listing>
		 */		
		public function Sprite(bitmap:TBitmap=null)
		{
			super();
			mRender=mRenderHelper
				   .getRender(NormalRender) as NormalRender;
			
			mRender.configureBackBuffer(Stage.width,Stage.height,4,true);
			
			mBitmap=bitmap;
			initBuffers();
			initModel();
		}
		public function set bitmap(value:TBitmap):void
		{
			if(mBitmap!=value)
			{
				mBitmap=value;
				initModel();
			}
			
		}
		private function initModel():void
		{
			if(mBitmap!=null)
			{
				mOrginWidth=mBitmap.width;
				mOrginHeight=mBitmap.height;
                mTexture=mBitmap.texture;
				mUVBuffer=mBitmap.uv;
				initSize();
			}
		}

		override public function set width(value:Number):void
		{
			mWidth=value;
			mAScaleX=(mWidth-mOrginWidth)/mOrginWidth+1;
			mAScaleX==0?mAScaleX=1:mAScaleX;
			
		}
		override public function set height(value:Number):void
		{
			mHeight=value;
			mAScaleY=(mHeight-mOrginHeight)/mOrginHeight+1;
			mAScaleY==0?mAScaleY=1:mAScaleY;
			
		}
		override protected function draw():void
		{
		    mRender.render(mVertexBuffer,
				           mUVBuffer,
						   mIndexBuffer,
						   mTexture,
						   mColors,
						   mCameraM3D,
						   mWorldMatrix);
		}
		
		public function startDrag(center:Boolean=false):void
		{
			mDragCenter=center;
			mDraged=true;
		}
		
		public function stopDrag():void
		{
			mDraged=false;
		}
		
	}
}